from lib.net.wlan import wlan_base
from lib.config.index import wifi_config
from utils import device
import network


class WLAN(wlan_base.WLAN):
    def __init__(self):
        super().__init__()
        network.hostname(self.__hostname)
        self.__wlan = network.WLAN(network.STA_IF)

    def connect(self):
        super().connect()
        
        if self.is_connected():
            return
        
        self.__wlan.active(True)
        tx_power = wifi_config.get_tx_power()
        if tx_power:
            self.__wlan.config(txpower=tx_power)
        if not self.__wlan.isconnected():
            print("wlan: connecting to network...")
        self.__wlan.connect(self.__ssid, self.__password)
        while not self.__wlan.isconnected():
            pass
        print(f"wlan: connect {self.__ssid} success")
        if wifi_config.is_debug():
            print("wlan: ifconfig:", self.__wlan.ifconfig())
        self.__status = WLAN.WLAN_STATUS["connected"]
        device.update_net_info()

    def disconnect(self):
        super().disconnect()
        if self.__wlan.isconnected():
            self.__wlan.disconnect()

    def is_connected(self):
        return self.__wlan.isconnected()
    
    def scan(self):
        buf = self.__wlan.scan()
        return buf
